<script lang="ts">
	import { Button, Drawer, CloseButton } from "flowbite-svelte";
	import { InfoCircleSolid } from "flowbite-svelte-icons";
	import { sineIn } from "svelte/easing";
	import { getNotificationsContext } from "svelte-notifications";

	// 导入图片上传网络请求函数
	import { uploadImageToServer } from "$lib/network/upload/Network";

	const { addNotification } = getNotificationsContext();

	let hidden6 = true;
	let uploading = false;
	let selectedFile: File | null = null;
	let imageUploaded = false;
	let autoCloseTimer: number | null = null;

	let transitionParamsRight = {
		x: 320,
		duration: 200,
		easing: sineIn,
	};

	function handleFileSelect(event: Event) {
		const input = event.target as HTMLInputElement;
		if (input.files && input.files.length > 0) {
			selectedFile = input.files[0];
		} else {
			console.log("null");
			selectedFile = null; // 如果没有文件，设置为空
		}
	}

	async function handleImageUpload() {
		if (!selectedFile) {
			showNotification("请选择图片", "error");
			return;
		}

		uploading = true;
		const formData = new FormData();
		if (selectedFile instanceof File) {
			const newFileName = "test.png"; // 设定新文件名

			const renamedFile = new File([selectedFile], newFileName, {
				type: selectedFile.type,
			});

			formData.append("file", renamedFile, renamedFile.name);
		} else {
			showNotification("上传文件无效", "error");
			uploading = false;
			return;
		}
		formData.forEach((value, key) => {
			console.log(key, value);
		});
		try {
			const res = await uploadImageToServer(formData);
			console.log('完整响应:', res); // 完整打印响应
			
			if (res.status === "success") {
				showNotification(res.message || `图片上传成功：${res.file_name}`, "success");
				// showNotification(`保存路径：${res.file_path}`, "info");

				// 新增：触发自定义事件，将 "@Image" 传递给父组件
				const event = new CustomEvent('imageUploaded', { 
					detail: { 
						imageText: "@Image" 
					} 
				});
				window.dispatchEvent(event);

				selectedFile = null;
				imageUploaded = true;

				// 2秒后自动关闭抽屉
				autoCloseTimer = setTimeout(() => {
					hidden6 = true;
				}, 2000) as unknown as number;

				// 重置文件输入
				const fileInput = document.getElementById(
					"imageUpload"
				) as HTMLInputElement;
				if (fileInput) fileInput.value = "";
			} else {
				const errorMessage = res.message || "图片上传失败，请重试";
				showNotification(`上传失败：${errorMessage}`, "error");
			}
		} catch (error) {
			const errorMsg = error instanceof Error ? error.message : String(error);
			console.error('上传错误:', error); // 增加错误日志
			showNotification(`上传出错：${errorMsg}`, "error");
		} finally {
			uploading = false;
		}
	}

	function showNotification(text: string, type: string) {
		addNotification({
			text: text,
			position: "top-left",
			type: type,
			removeAfter: 3000,
		});
	}

	// 重置上传状态的函数
	function resetUploadStatus() {
		imageUploaded = false;
		selectedFile = null;
		
		// 清除自动关闭定时器
		if (autoCloseTimer) {
			clearTimeout(autoCloseTimer);
			autoCloseTimer = null;
		}
	}

	// 自定义关闭处理函数，不重置状态
	function handleDrawerClose() {
		hidden6 = true;
	}
</script>

<div class="ml-[10px] flex items-center justify-center text-center">
	<Button
		on:click={() => {
			hidden6 = false;
			resetUploadStatus(); // 重置上传状态
		}}
		class="rounded-lg px-4 py-2 text-white {imageUploaded ? 'bg-gray-400' : 'bg-blue-500 hover:bg-blue-600'}"
		data-testid="open-upload-image"
	>
		{imageUploaded ? '图片已上传' : '选择图片'}
	</Button>
</div>

<Drawer
	backdrop={false}
	placement="right"
	transitionType="fly"
	transitionParams={transitionParamsRight}
	bind:hidden={hidden6}
	class="border-2 border-b-0 border-r-0 shadow"
>
	<div class="flex items-center">
		<h5
			class="mb-4 inline-flex items-center text-base font-semibold text-gray-500 dark:text-gray-400"
		>
			<InfoCircleSolid class="me-2.5 h-4 w-4" />图片上传
		</h5>
		<CloseButton
			on:click={handleDrawerClose}
			class="mb-4 dark:text-white"
		/>
	</div>

	<div class="mb-6">
		<input
			type="file"
			id="imageUpload"
			accept="image/*"
			on:change={handleFileSelect}
			disabled={imageUploaded}
			class="block w-full cursor-pointer rounded-lg border border-gray-300 bg-gray-50 text-sm text-gray-900 focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:text-gray-400 dark:placeholder-gray-400 {imageUploaded ? 'opacity-50 cursor-not-allowed' : ''}"
		/>
	</div>

	{#if selectedFile}
		<div class="mb-6">
			<p class="text-sm text-gray-500">已选择文件: {selectedFile.name}</p>
		</div>
	{/if}

	<Button
		on:click={handleImageUpload}
		disabled={!selectedFile || uploading || imageUploaded}
		class="w-full"
	>
		{#if uploading}
			上传中...
		{:else if imageUploaded}
			已上传
		{:else}
			上传图片
		{/if}
	</Button>
</Drawer>